//
//  GeoJson.m
//  Trackit
//
//  Created by yaodaobin on 2017/4/18.
//  Copyright © 2017年 yaodaobin. All rights reserved.
//

#import "GeoJson.h"

@implementation GeoJson

- (instancetype)initWithDictionary:(NSDictionary *)dictionary {
    self = [super init];
    if (self) {
        self.type = [CommonFunction getValueFromDic:dictionary withKey:@"type"];
        NSMutableArray *array = [NSMutableArray array];
        for (NSDictionary *dic in dictionary[@"features"]) {
            GeoFeature *feature = [[GeoFeature alloc] initWithDictionary:dic];
            [array addObject:feature];
        }
        self.features = array;
    }
    return self;
}

- (NSMutableArray<GeoFeature *> *)features {
    if (!_features) {
        _features = [NSMutableArray array];
    }
    return _features;
}

+ (NSMutableDictionary *)getGeoJson:(GeoJson *)geoJson {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic safeSetObject:geoJson.type forKey:@"type"];
    
    NSMutableArray *array = [NSMutableArray array];
    for (GeoFeature *feature in geoJson.features) {
        NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
        [tempDic safeSetObject:feature.type forKey:@"type"];
        [tempDic safeSetObject:feature.properties forKey:@"properties"];
        
        NSMutableDictionary *tempDic1 = [NSMutableDictionary dictionary];
        GeoMetry *metry = feature.geoMetry;
        [tempDic1 safeSetObject:[GeoMetry translateToGeometryTypeString:metry.type] forKey:@"type"];
        [tempDic1 safeSetObject:metry.coordinates forKey:@"coordinates"];
        
        [tempDic safeSetObject:tempDic1 forKey:@"geometry"];
        [array addObject:tempDic];
    }
    [dic safeSetObject:array forKey:@"features"];
    return dic;
}

+ (void)saveJsonToCache:(NSString *)idString geoJson:(GeoJson *)geoJson {
    NSString *filePath = [[CommonFunction getTrackitCachePathByID:idString] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.json",idString]];
    NSLog(@"%@",filePath);
    NSDictionary *json_dic = [self getGeoJson:geoJson];
    NSData *json_data = [NSJSONSerialization dataWithJSONObject:json_dic options:NSJSONWritingPrettyPrinted error:nil];
    BOOL success = [json_data writeToFile:filePath atomically:YES];
    if (success) {
        [GeoJson deleteGeoFeatureCache:idString];
    }
}

+ (void)saveImagesToCache:(NSString *)idString images:(NSArray *)images {
    NSMutableArray *array = APP_DELEGATE.user.localImageUrlPathDictionary[idString];
    if (!array) {
        array = [NSMutableArray array];
    }

    NSFileManager *fileManager = [NSFileManager defaultManager];

    for (UploadImageInfo *info in images) {
        NSString *filePath = [CommonFunction getTrackitCachePathByID:idString];
        if ([fileManager fileExistsAtPath:filePath]) {
            NSData *imageData = UIImageJPEGRepresentation(info.image, 0.9f);
            
            filePath = [filePath stringByAppendingPathComponent:info.localPath];
            BOOL success = [imageData writeToFile:filePath atomically:YES];
            if (success) {
                [array addObject:filePath];
            }
        }
    }
    [APP_DELEGATE.user.localImageUrlPathDictionary setValue:array forKey:idString];
}

+ (void)deleteImagesCache:(NSString *)idString paths:(NSArray *)paths {
    NSMutableArray *array = APP_DELEGATE.user.localImageUrlPathDictionary[idString];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    for (NSString *path in paths) {
        if ([fileManager fileExistsAtPath:path]) {
            [fileManager removeItemAtPath:path error:nil];
        }
        if ([array containsObject:path]) {
            [array removeObject:path];
        }
    }
    [APP_DELEGATE.user.localImageUrlPathDictionary setValue:array forKey:idString];

}

+ (BOOL)deleteTaskCache:(NSString *)idString {
    [APP_DELEGATE.user.localImageUrlPathDictionary setValue:nil forKey:idString];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [CommonFunction getTrackitCachePathByID:idString];
    if ([fileManager fileExistsAtPath:filePath]) {
        return [fileManager removeItemAtPath:filePath error:nil];
    }
    return NO;
}

+ (BOOL)deleteAllCache {
    [APP_DELEGATE.user.localImageUrlPathDictionary removeAllObjects];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = [CommonFunction getCachePath];
    if ([fileManager fileExistsAtPath:path]) {
        return [fileManager removeItemAtPath:path error:nil];
    }
    return NO;
}

+ (BOOL)deleteJsonCache:(NSString *)idString {
    NSString *filePath = [[CommonFunction getTrackitCachePathByID:idString] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.json",idString]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        return [fileManager removeItemAtPath:filePath error:nil];
    }
    return NO;
}

+ (NSArray <UIImage *>*)getCacheImages:(NSArray *)localPaths {
    NSMutableArray *array = [NSMutableArray array];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    for (NSString *localPath in localPaths) {
        NSString *filePath = [[CommonFunction getTrackitCachePathByID:localPath] stringByAppendingString:@".jpg"];
        NSLog(@"%@",filePath);
        if ([fileManager fileExistsAtPath:filePath]) {
            NSData *imageData = [NSData dataWithContentsOfFile:filePath];
            UIImage *image = [UIImage imageWithData:imageData];
            [array addObject:image];
        }
    }
    return [NSArray arrayWithArray:array];
}

+ (GeoJson *)getGeoJsonFromCache:(NSString *)idString {
    NSString *filePath = [[CommonFunction getTrackitCachePathByID:idString] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.json",idString]];
    NSLog(@"%@",filePath);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        return [self parseGeojsonWithDictionary:jsonDict];
    }
    
    return nil;
}

+ (NSMutableDictionary *)getFeature:(GeoFeature *)feature {
    NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
    [tempDic safeSetObject:feature.type forKey:@"type"];
    [tempDic safeSetObject:feature.properties forKey:@"properties"];
    
    NSMutableDictionary *tempDic1 = [NSMutableDictionary dictionary];
    GeoMetry *metry = feature.geoMetry;
    [tempDic1 safeSetObject:[GeoMetry translateToGeometryTypeString:metry.type] forKey:@"type"];
    [tempDic1 safeSetObject:metry.coordinates forKey:@"coordinates"];
    
    [tempDic safeSetObject:tempDic1 forKey:@"geometry"];
    return tempDic;
}

+ (GeoFeature *)getGeoFeatureFromCache:(NSString *)idString {
    NSString *filePath = [[CommonFunction getTrackitCachePathByID:idString] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_temp.json",idString]];
    NSLog(@"%@",filePath);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        return [self parseGeoFeatureWithDictionary:jsonDict];
    }
    return nil;
}

+ (BOOL)saveFeatureToCache:(NSString *)idString feature:(GeoFeature *)feature {
    NSString *filePath = [[CommonFunction getTrackitCachePathByID:idString] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_temp.json",idString]];
    NSLog(@"%@",filePath);
    NSDictionary *json_dic = [self getFeature:feature];
    NSData *json_data = [NSJSONSerialization dataWithJSONObject:json_dic options:NSJSONWritingPrettyPrinted error:nil];
    return [json_data writeToFile:filePath atomically:YES];

}

+ (BOOL)deleteGeoFeatureCache:(NSString *)idString {
    NSString *filePath = [[CommonFunction getTrackitCachePathByID:idString] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_temp.json",idString]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        return [fileManager removeItemAtPath:filePath error:nil];
    }
    return NO;
}

#pragma mark - Private
+ (GeoJson *)parseGeojsonWithDictionary:(NSDictionary *)dic {
    if (!dic || dic.count == 0) {
        return nil;
    }
    GeoJson *geoJson = [[GeoJson alloc] initWithDictionary:dic];
    return geoJson;
}

+ (GeoFeature *)parseGeoFeatureWithDictionary:(NSDictionary *)dic {
    if (!dic || dic.count == 0) {
        return nil;
    }
    GeoFeature *feature = [[GeoFeature alloc] initWithDictionary:dic];
    return feature;
}

@end
